<template>
  <div class="bg-white my-[10px]">
    <BaseHead style="border-bottom: 0">
      校内课题 <el-button @click="handleAdd">添加</el-button></BaseHead
    >
    <el-table :data="subjectList" class="w-full" border stripe>
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column label="课题名称">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-input v-model="row.projectName" placeholder="" clearable />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="projectLeader" label="课题负责人">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-autocomplete
              v-model="row.projectLeader"
              :fetch-suggestions="personSearch(row)"
              clearable
              value-key="name"
              :trigger-on-focus="false"
              @select="selectPerson(row, $event)"
              @blur="selectPerosnBlur(row, $event)"
            >
              <template #default="{ item }">
                <span>{{ item.name }}</span>
                <span class="mx-[10px]">{{ item.account }}</span>
                <span>{{ item.unitName }}</span>
              </template>
            </el-autocomplete>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="所属单位">
        <template #default="{ row }">
          <CommonTreeSelect
            placeholder="所属单位"
            v-model="row.projectUnit"
            valueKey="codeColumn"
            labelKey="valueColumn"
            :isFetch="false"
            :dataList="unitList"
          />
        </template>
      </el-table-column>
      <el-table-column label="批准经费（万元）">
        <template #default="{ row }">
          <div class="flex items-center">
            <span class="no-empty-icon">*</span>
            <el-input
              v-model="row.projectFee"
              clearable
              @input="fomateNumber(row, 'projectFee', $event)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="100" align="center">
        <template #default="{ row, $index }">
          <el-button type="primary" size="small" plain @click="handleDel($index)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import { schoolSubjectDetail, editSchoolSubject } from "@/api/project/zx/lxxm";
import { getPersonList } from "@/api/project/common";
import { ElMessage } from "element-plus";
import { fomateNumber } from "@/utils/main";
const unitList = inject("unitList");
const subjectList = ref([]);
const operateId = ref(null);
const totalFee = ref(0); //主项目批准经费
const outFee = ref(0); //外拨经费
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
//初始化一个课题项 用于添加
const initSubjectItem = () => {
  return {
    projectId: operateId.value,
    projectName: "", //课题名称
    projectLeader: "", //课题负责人
    projectLeaderPersonid: "", //负责人id
    projectUnit: "", //所属单位id
    projectFee: "", //批准经费
  };
};
//点击添加按钮
const handleAdd = () => {
  subjectList.value.push(Object.assign({}, initSubjectItem()));
};
//点击删除按钮删除一行
const handleDel = (index) => {
  subjectList.value.splice(index, 1);
};
//获取校内课题信息详情
const getSubjectDetail = async () => {
  try {
    const res = await schoolSubjectDetail(operateId.value);
    subjectList.value = res.data.bizProjectInSchoolList;
    totalFee.value = parseFloat(res.data.proInitOtherBaseInfoVo.feeAuthorize);
    outFee.value = parseFloat(res.data.proInitOtherBaseInfoVo.outFee);
  } catch (error) {
    console.log(error);
  }
};
//编辑
const edit = async (id) => {
  operateId.value = id;
  //获取单位列表
  getSubjectDetail();
};
//搜索人员列表
const personSearch = (row) => {
  return async (queryString, cb) => {
    if (queryString.trim() == "") {
      return;
    }
    row.projectLeaderPersonid = "";
    const params = {
      name: queryString,
    };
    try {
      const res = await getPersonList(params);
      cb(res.data);
    } catch (error) {
      console.log(error);
    }
  };
};
//选择成员改变
const selectPerson = (row, val) => {
  row.projectUnit = val.unitId;
  row.projectLeaderPersonid = val.id;
};
const selectPerosnBlur = (row) => {
  if (!row.projectLeaderPersonid) {
    row.projectLeader = "";
    row.projectUnit = "";
    row.projectLeaderPersonid = "";
  }
};
const emit = defineEmits(["save-success", "save-ok"]);
//保存
const save = async (submitType) => {
  try {
    //判断校内课题批准经费之和是否等于主项目批准经费减外拨经费
    let total = 0;
    subjectList.value.forEach((item) => {
      total += parseFloat(item.projectFee);
    });
    if (total != totalFee.value - outFee.value) {
      ElMessage({
        message: "校内课题批准经费之和不等于主项目批准经费减外拨经费！",
        type: "error",
      });
      return;
    }
    const params = {
      proId: operateId.value,
      submitType,
      isAuditor: isAuditor.value,
      taskId: taskId.value,
      checkstatus: checkStatus.value,
      slaveTableList: subjectList.value,
    };
    const res = await editSchoolSubject(params);
    if (res.code === 200) {
      emit("save-success");
    }
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ edit, save });
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
